package com.mzw.huaxiarealestatebackend.controller;
import com.mzw.huaxiarealestatebackend.common.utils.DataResult;
import com.mzw.huaxiarealestatebackend.entity.Client;
import com.mzw.huaxiarealestatebackend.service.ClientService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;

/**
 * (Client)表控制层
 *
 * @author makejava
 * @since 2023-12-11 16:21:46
 */
@RestController
@RequestMapping("client")
public class ClientController {
    /**
     * 服务对象
     */
    @Resource
    private ClientService clientService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public DataResult queryAll(){
        List<Client> clients = this.clientService.queryAll();
        //判断是否有数据
        boolean isEmpty = clients.isEmpty();
        return new DataResult(isEmpty ? 403 : 200, isEmpty ? "查询失败" : "查询成功", clients);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public DataResult queryById(@PathVariable("id") String id) {
        Client client = this.clientService.queryById(id);
        //判断是否有数据
        boolean isEmpty = client == null;
        return new DataResult(isEmpty ? 403 : 200, isEmpty ? "查询失败" : "查询成功", client);
    }

    /**
     * 模糊查询
     * @param client
     * @return
     */
    @PostMapping("/queryByCondition")
    public DataResult queryByCondition(@RequestBody Client client){
        List<Client> clients = this.clientService.queryByCondition(client);
        //判断是否有数据
        boolean isEmpty = clients.isEmpty();
        return new DataResult(isEmpty ? 403 : 200, isEmpty ? "查询失败" : "查询成功", clients);
    }


    /**
     * 新增数据
     *
     * @param client 实体
     * @return 新增结果
     */
    @PostMapping
    public DataResult add(@RequestBody Client client) {
        try {
            boolean insert = this.clientService.insert(client);
            if (insert) {
                return DataResult.ok();
            } else {
                return DataResult.failure("用户已存在");
            }
        } catch (DuplicateKeyException e) {
            // 处理主键（唯一约束）冲突
            return DataResult.failure("用户已存在");
        } catch (Exception e) {
            // 处理其他异常
            return DataResult.failure("新增失败，发生异常");
        }
    }

    /**
     * 编辑数据
     *
     * @param client 实体
     * @return 编辑结果
     */
    @PutMapping
    public DataResult edit(@RequestBody Client client) {
        boolean update = this.clientService.update(client);
        if (update){
            return DataResult.ok("修改成功");
        }else {
            return DataResult.failure("修改失败");
        }
    }

}

